<template>
    <div class="main_container">
        <TopBanner />
        <div class="content_container">
            <TodoInput @add-new-todo-item="onAddNewTodoItem" />
            <TodoItem v-for="todoTask, index in todoTaskList" :key="todoTask.taskId" 
                :todoTask="todoTask"
                @completed="onCompleted" @delete-item="onDeleteItem" />
            <BottomItem v-if="todoTaskList.length > 0"
                :todoTaskList="todoTaskList"
                :onDeleteCompleted="onDeleteCompleted" />
        </div>
    </div>

</template>

<script setup>
    import { reactive, watch } from 'vue';
    import TodoInput from '../components/TodoInput.vue';
    import TopBanner from '../components/TopBanner.vue';
    import TodoItem from '../components/TodoItem.vue';
    import BottomItem from '../components/BottomItem.vue'; 

    defineEmits(["vnode-unmounted"])

    let todoTaskList = reactive(JSON.parse(localStorage.getItem("todoTaskStore")) || [])

    watch(todoTaskList, (newVal)=>{
        localStorage.setItem("todoTaskStore", JSON.stringify(newVal))
    })

    function onAddNewTodoItem(todoTask) {
        if (todoTask) {
            todoTaskList.push(todoTask)
            console.log("Main.vue, todoTaskList=" + todoTaskList)
        }
    }

    function onCompleted(taskId) {
        for (let index = 0; index < todoTaskList.length; index++) {
            if (todoTaskList.at(index).taskId === taskId) {
                todoTaskList.at(index).isCompleted = !todoTaskList.at(index).isCompleted;
                return
            }
        }
    }

    function onDeleteItem(taskId) {
        console.log("onDeleteItem(), taskId=" + taskId)
        if (confirm("确定要删除该任务?")) {
            for (let index = 0; index < todoTaskList.length; index++) {
                if (todoTaskList.at(index).taskId === taskId) {
                    todoTaskList.splice(index, 1)
                    return
                }
            }
        }
    }

    function onDeleteCompleted() {
        const deleteTodoTaskIds = []
        for (let index = todoTaskList.length - 1; index >= 0; index--) {
            if (todoTaskList.at(index).isCompleted) {
                deleteTodoTaskIds.push(index)
            }
        }
        if (deleteTodoTaskIds.length > 0) {
            if (confirm("确定要删除所有已完成的任务?")) {
                for(const index of deleteTodoTaskIds) {
                    todoTaskList.splice(index, 1)
                }
            }
        } else {
            alert("没有完成的任务")
        }
    }

</script>

<style scoped>
    .main_container {
        display: flex;
        flex-direction: column;
    }

    .content_container {
        box-sizing: border-box;
        margin-top: 20px;
        width: 70%;
        border-radius: 5px;
        border-color: gray;
        border-width: 2px;
        border-style: solid;
        align-self: center;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
</style>